package com.syp.test.clustercacheflush.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.syp.test.clustercacheflush.domain.TaskEntity;
import com.syp.test.clustercacheflush.handler.TaskProcessHandler;
import com.syp.test.clustercacheflush.util.SpringContextUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class QuickTaskProcessService {

	@Resource(name = "quickTaskProcessExecutor")
	private ThreadPoolTaskExecutor quickTaskProcessExecutor;
	@Autowired
	private TaskService taskService;

	public void process(TaskEntity task) {
		if (task.getTaskStatus() != TaskStatus.LOCK.getStatus()) {
			log.info("任务目前并没有或者执行锁，本次不执行该任务:{}。", task);
			return;
		}
		this.quickTaskProcessExecutor.execute(() -> {
			boolean done = false;
			try {
				log.debug("执行任务内容:{}", JSON.toJSONString(task));
				TaskType taskType = TaskType.get(task.getTaskType());
				TaskProcessHandler processor = SpringContextUtil.getBean(taskType.getExecutor());
				done = processor.process(task);
				if (done) {
					this.taskService.finish(task);
				}
			} catch (Exception e) {
				log.error("执行任务异常:{}", e);
			}
		});
	}
}
